package com.twm.controller;

import cn.hutool.captcha.CircleCaptcha;
import com.twm.common.BaseController;
import com.twm.common.CommonEnum;
import com.twm.common.ResponseMessage;
import com.twm.common.StatusCode;
import com.twm.redis.RedisService;
import com.twm.register.LoginService;
import com.twm.util.CookieUtil;
import com.twm.util.DateUtil;
import com.twm.util.HttpResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

import static com.twm.common.CommonEnum.LOGIN_URL;


/**
 * @ClassName LoginController
 * @Description TODO
 * @Author twm17
 * @Date 2020/11/11 15:53
 * @Version 1.0
 */
@RestController
public class LoginController extends BaseController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private RedisService redisService;

    @PostMapping(LOGIN_URL)
    public ResponseMessage login(@RequestParam("account") String account,
                                 @RequestParam("password") String password,
                                 @RequestParam("checkcode")String checkcode) {

        String cookieValue = CookieUtil.getCookieValue(this.request, CommonEnum.IMAGE_CHECK_CODE);
        String code = redisService.get(checkcode);
        if (!checkcode.toLowerCase().equals(code)) {
            return new ResponseMessage(StatusCode.CODE_ERROR.getStatus(),StatusCode.CODE_ERROR.getMessage());
        }
        return loginService.login(account,password);
    }

    @GetMapping("getimagecode")
    public void getImageCheckCode(HttpServletResponse response) throws IOException {
        CircleCaptcha captcha = loginService.getImageCheckCode();
        String code = captcha.getCode();
        String keyUUID = UUID.randomUUID().toString() + LocalDateTime.now().toString();
        redisService.setEx(keyUUID,code.toLowerCase(), DateUtil.RedisCacheExtime.REDIS_SESSION_EXTIME_2);
        HttpResponseUtil.writeResponseCookie(response, CommonEnum.IMAGE_CHECK_CODE,keyUUID);
        HttpResponseUtil.writeResponseContene(response, captcha.getImageBytes());
    }
}
